package com.dabai.simpleconnection.utils;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NotificationUtils;
import com.dabai.simpleconnection.R;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Description : Other
 *
 * @author BAI
 */
public class SendFileUtils {


    /**
     * 发送文件
     *
     * @param file     文件
     * @param activity 活动
     * @param client   客户端
     */
    public static void sendFile(Activity activity, Socket client, File file) {

        TipAlertDialog.getInstance(activity).showTipLayout("正在准备文件...");

        new Thread(() -> {

            try {

                FileInputStream fis = new FileInputStream(file);
                //BufferedInputStream bi=new BufferedInputStream(new InputStreamReader(new FileInputStream(file),"GBK"));
                OutputStream dos = client.getOutputStream();//client.getOutputStream()返回此套接字的输出流

                byte[] bytes = new byte[1024];
                int length;

                long count = 0;

                while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                    dos.write(bytes, 0, length);
                    dos.flush();
                    count += length;
                    long finalCount = count;
                    activity.runOnUiThread(() -> {
                        TipAlertDialog.getInstance(activity).showTipLayout("正在发送到" + client.getInetAddress().getHostAddress() + "\n("
                                + (int) (((float) finalCount / (float) file.length()) * 100)
                                + "%)");
                    });
                }

                activity.runOnUiThread(() -> {
                    TipAlertDialog.getInstance(activity).hideTipLayout();
                    DBToast.showText(activity, "发送完成!", true);
                    // FileUtils.delete(file);
                });

            } catch (IOException e) {
                FileUtils.delete(file);
                Log.d("DBTAG", "发送失败: " + e.getMessage());
                activity.runOnUiThread(() -> {
                    TipAlertDialog.getInstance(activity).hideTipLayout();
                });
            }

        }).start();

    }


}
